<template>
	<Menu 
		ref="sider-ul"
		theme="dark" 
		:open-names="openedNames"
		:active-name="activeName"
		accordion 
		width="200" 
		@on-select="changeMenu"
		@on-open-change="openMenu"
		class="sider-ul">
    
    
        <Submenu :name="level1.name" v-for="(level1,index1) in routeList" v-if="level1.hidden" :key="level1.name+index1" class="menu-level-1" :class="getMenuclass(level1)">
            <template slot="title">
            	<div class="menu-item-wrapper" :style="{color:showMark(level1) ? 'var(--first-menu-active-color)':'var(--menu-default-color)'}">
					<Icon v-if="level1.icon" :type="level1.icon" :class="handleClass(level1,'icon')" :size="16"></Icon>
	                <div v-else :class="handleClass(level1)" class="menu-icon"></div>
	                <span>{{level1.title}} </span>
                </div>
            </template>
            <template v-for="(level2,index2) in level1.children">
            	<template v-if="level2.children && level2.hidden">
					<Submenu :name="level2.name" class="menu-level-2">
						<template #title>{{level2.title}}</template>
						<MenuItem 
                        	v-if="level3.hidden"
                        	:name="level3.name" 
                        	v-for="(level3,index3) in level2.children" 
                        	:key="level3.name+index3">
                        	{{level3.title}}
                        </MenuItem>
					</Submenu>
            		<!-- <MenuGroup :title="level2.title" :key="level2.name">
                        <MenuItem 
                        	v-if="level3.hidden"
                        	:name="level3.name" 
                        	v-for="level3 in level2.children" 
                        	:key="level3.name">
                        	{{level3.title}}
                        </MenuItem>
                    </MenuGroup> -->
            	</template>
            	<template v-else>
            		<MenuItem 
            			v-if="level2.hidden"
            			:name="level2.name" 
            			:key="level2.name+index2" >
            			{{level2.title}}
            		</MenuItem>
            	</template>
            </template>
        </Submenu>
    </Menu>
</template>
<script>
	import {mapState,mapMutations} from 'vuex'
	export default {
		name: 'SideMenu',
		mixins: [],
		components: {

		},
		props: {
			activeNames: {
				type: Array,
				default: () => []
			},
			routeList: {
				type: Array,
				default: () => []
			},
			height: ''
		},
		data() {
			return {
        // map:key为 路由的name,value ：是父辈路由name的数组，
        // 比如子菜单user是memberManagement的子菜单那么： user:["memberManagement", "user"]
        menu2Paths:{},
				activeMenuList: [],
				menuListAll:[],
				menuListAllHidden:[],
				menuListAllShow:[],
				openedNames:[],
				activeName:''
			}
		},
		methods: {
            ...mapMutations(["setMenuInfo","clearBreadList"]),
      getMenuclass(level1){
        let hasChild = (level1.children &&level1.children.length>0)?' ':' ivu-menu-noChild'
        let c1 = this.activeName === level1.name ? 'activeMenu' : '' // :class="activeName === level1.name ? 'activeMenu' : ''"
        if(level1.children===undefined && c1==='activeMenu'){
          c1 +=' ivu-menu-child-item-active'
        }
        return c1+' '+hasChild
      },
			showMark(menu) {
				return this.activeMenuList.includes(menu.name);
			},
			hasChildren(menu){
				return menu.children && menu.children.filter(menu => menu.hidden).length > 0;
			},
			//			markRoute(activeList, routeList) {
			//				routeList.forEach(route => {
			//					if(activeList.includes(route.name) && route.hidden) {
			//						route.meta.mark = true
			//					} else {
			//						if(route.meta) {
			//							route.meta.mark = false
			//						}
			//					}
			//					if(route.children) {
			//						this.markRoute(activeList, route.children)
			//					}
			//				})
			//			},
			flatDeep(arr, d = 1, result = []) {
				if(d > 0) {
					for(let item of arr) {
						if(Array.isArray(item.children)) {
							result.push(item)
							this.flatDeep(item.children, Infinity, result)
						} else {
							result.push(item)
						}
					}
					return result
				} else {
					return arr.slice();
				}
			},
			routeHasHidden(name) {
				return this.menuListAllHidden.find(menu => menu.name == name);
			},
			//根据子菜单获取一级菜单
			getLevel1Menu(name) {
				let menu = this.menuListAll.find(route => route.name == name);
				if(menu && menu.parentRoute) {
					return this.getLevel1Menu(menu.parentRoute.name);
				} else {
					return menu;
				}
			},
			gotoOtherShowRoute(name) {
				//获取当前菜单信息
				let menuInfo = this.menuListAll.find(route => route.name == name);
				if(menuInfo && menuInfo.parentRoute) { //如果当前菜单是子菜单（二级/三级）
					//获取一级父菜单信息
					let level1Menu = this.getLevel1Menu(menuInfo.name);
					//获取父级菜单
					let pmenu = menuInfo.parentRoute;
					if(level1Menu.hidden) { //如果一级菜单显示
						if(menuInfo.level == 2) { //二级
							//获取对当前菜单的同级菜单
							let siblingsMenu = menuInfo.parentRoute.children;//this.menuListAll.filter(menu => menu.pid == menuInfo.pid);
							let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
							if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
								let firstShowRoute = siblingsShowMenu;
								this.changeMenuItem(firstShowRoute, level1Menu);
							} else {
								this.gotoOtherShowRoute(level1Menu.name);
							}
						} else { //三级
							if(pmenu.hidden) {//二级菜单显示
								let siblingsMenu = menuInfo.parentRoute.children;//this.menuListAll.filter(menu => menu.pid == menuInfo.pid);
								let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
								if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
									let firstShowRoute = siblingsShowMenu;
									this.changeMenuItem(firstShowRoute, level1Menu);
								}
							} else { //二级菜单隐藏
								//获取父级菜单的兄弟菜单
								let siblingsMenu = level1Menu.children;
								let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
								if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
									let firstShowRoute = siblingsShowMenu;
									this.changeMenuItem(firstShowRoute.children ? firstShowRoute.children[0] : firstShowRoute);
								} else {
									this.gotoOtherShowRoute(level1Menu.name);
								}
							}
						}
					} else { //一级菜单隐藏
						this.gotoOtherShowRoute(level1Menu.name);
					}
				} else {
					let firstShowRoute = this.menuListAllShow.length > 0 ? this.menuListAllShow[0] : '';
					if(firstShowRoute) { //有显示的路由
						this.changeMenuItem(firstShowRoute);
					} else {
						this.$Message.warning('没有可用的菜单');
						setTimeout(() => {
							this.$emit('on-select', 'login')
						})
					}
				}
			},
			// 设置icon
			handleClass(value,type) {
				let {
					defClass,
					activeClass,
					mark
				} = value.meta;
				return this.showMark(value) ? (type == 'icon' ? 'icon-active' : activeClass) : (type == 'icon' ? 'icon-def' : defClass)
			},
			changeMenu(name){
				let menu = this.menuListAllShow.find(menu => menu.name == name);
				this.changeMenuItem(menu);
			},
			openMenu(menus){
				let menu = this.menuListAllShow.find(menu => menu.name == menus[menus.length - 1]);
				this.changeMenuItem(menu);
			},
			// 切换导航栏
			changeMenuItem(menu, level1Menu) { //当前菜单，一级菜单
				if(!menu){
					return
				}
				let name = menu.name;
				let level = menu.level;
				let children = menu.children;
				let markMenuObj = sessionStorage.getItem('markMenuObj') ? JSON.parse(sessionStorage.getItem('markMenuObj')) : {};
				if(level == 1) {
					// 切换时是否跳到上次点击的子菜单栏
					let prevMarkName = markMenuObj[name];
					if(prevMarkName) {
						this.activeMenuList = this.getActiveMenuList(prevMarkName)
						this.$emit('on-select', prevMarkName)
					} else {
						this.activeMenuList = this.getActiveMenuList(name)
						this.$emit('on-select', name)
					}
				} else {
					this.activeMenuList = this.getActiveMenuList(name)
					this.$emit('on-select', name)
				}
				this.clearBreadList()
			},
			getActiveMenuList(name,list = []){ //根据当前菜单找到所有的父级菜单
				if(!name){
					return list;
				}
				let menu = this.menuListAll.find(route => route.name == name);
				list.unshift(name);
				if(menu && menu.parentRoute) {
					let pMenu = menu.parentRoute;
					return this.getActiveMenuList(pMenu.name,list);
				} else {
					return list;
				}
			},
      // openedNames---- [ "memberManagement", "user" ]---
      url2Parent(list,paths){
              // menu2Paths
        list.forEach(item=>{
          let newpaths = JSON.parse(JSON.stringify(paths))// 深拷贝
          newpaths.push(item.name)
          this.menu2Paths[item.name] = newpaths
          if(item.children && item.children.length>0){
            this.url2Parent(item.children,newpaths)
          }
        })
        
      },
      
			initRoute(){ //设置当前mark的菜单列表及菜单显示位置
  
      
        let activeMenuList = this.menu2Paths[this.$route.name]
        if(!activeMenuList){
          activeMenuList = this.$route.matched.map(item => item.name).filter(item => item !== 'main');
        }
        //console.log('----获取的路由啊啊--------',this.activeMenuList)
        
        
				let storageMenuList = sessionStorage.getItem('activeMenuList');
				storageMenuList = storageMenuList && JSON.parse(storageMenuList) || [];
				let markMenuObj = sessionStorage.getItem('markMenuObj') ? JSON.parse(sessionStorage.getItem('markMenuObj')) : {};
				let activeName = '';
				if(activeMenuList.length > 0) {
					if(activeMenuList[0] == 'parentView') { //非菜单页
						//多个路由跳转同一个页面配置
						let setActiveMenuList = []
						activeName = this.$route.meta.activeName;
						let fromMenu = this.$route.query.fromMenu
						if((activeName && typeof activeName === 'string') || fromMenu === 'homer'){
							if(Array.isArray(activeName)){
								activeName = activeName[0]
							}
							setActiveMenuList = this.getActiveMenuList(activeName);
						}else if(fromMenu){
							setActiveMenuList = this.getActiveMenuList(fromMenu);
						}
						if(JSON.stringify(storageMenuList) != JSON.stringify(setActiveMenuList)){ //如果详情页设置的高亮菜单和存储的高亮菜单不一致,说明详情页需要高亮的菜单和当前高亮的菜单不匹配（以详情页为主）
							if(setActiveMenuList.length > 0){
								this.activeMenuList = setActiveMenuList; //重新设置触发菜单
								activeName = this.activeMenuList[this.activeMenuList.length - 1];
								// this.$router.push(activeName);
//								sessionStorage.setItem('activeMenuList', JSON.stringify(this.activeMenuList));
//								if(this.activeMenuList.length > 1) {
//									markMenuObj[this.activeMenuList[0]] = activeName;
//									sessionStorage.setItem('markMenuObj', JSON.stringify(markMenuObj));
//								}
							}else{
								if(storageMenuList.length > 0) {
									this.activeMenuList = storageMenuList;
									activeName = this.activeMenuList[this.activeMenuList.length - 1];
								} else {
									let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
									this.$emit('on-select', toName);
									return;
								}
							}
						}else{
							if(storageMenuList.length > 0) {
								this.activeMenuList = storageMenuList;
								activeName = this.activeMenuList[this.activeMenuList.length - 1];
							} else if(setActiveMenuList.length > 0){
								this.activeMenuList = setActiveMenuList;
								activeName = this.activeMenuList[this.activeMenuList.length - 1];
							}else{
								let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
									this.$emit('on-select', toName);
								return;
							}
						}
					} else { //菜单页
						this.activeMenuList = activeMenuList;
						activeName = this.activeMenuList[this.activeMenuList.length - 1];
						this.clearBreadList();
						//记录当前菜单
						sessionStorage.setItem('activeMenuList', JSON.stringify(this.activeMenuList))
						if(activeMenuList.length > 1) {
							markMenuObj[this.activeMenuList[0]] = activeName;
							sessionStorage.setItem('markMenuObj', JSON.stringify(markMenuObj));
						}
					}
					this.openedNames = this.activeMenuList //.length === 1 ? this.activeMenuList : this.activeMenuList.slice(0,this.activeMenuList.length - 1);
					this.activeName = activeName;
				} else {
					if(storageMenuList.length > 0) {
						this.$emit('on-select', storageMenuList[storageMenuList.length - 1])
						return;
					} else {
						let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
						this.$emit('on-select', toName)
						return;
					}
				}
				if(this.routeHasHidden(activeName)) {
					this.gotoOtherShowRoute(activeName);
					return;
				}
				//菜单滚动位置
				this.$nextTick(() => {
					let oUl = document.getElementsByClassName("sider-ul")[0];
					let el = document.getElementById('menu-' + this.activeMenuList[0]);
					if(oUl && el) {
						oUl.scrollTop = (el.offsetTop - oUl.offsetTop) - (oUl.offsetHeight - el.offsetHeight) / 2;
					}
				})
			},
			setMenuLevel(routeList,parentRoute,level = 0){
				level++;
				routeList.forEach(route => {
					route.level = level;
					if(parentRoute){
						route.parentRoute = parentRoute;
					}
					if(route.children && route.children.length > 0){
						this.setMenuLevel(route.children,route,level);
					}
				})
			},
		},
		computed: {
			// ...mapState(['projectName',rourouteList:'routeList']),
      //
      ...mapState({
        projectName: 'projectName',
        routeListState: 'routeList'
      })
		},
		beforeDestroy() {
			sessionStorage.removeItem('markMenuObj');
			sessionStorage.removeItem('activeMenuList');
		},
		updated() {

		},
		watch: {
			activeNames(val) {
				this.initRoute();
			},
            activeMenuList(val,oldVal){
				if(val.length > 0){
					let menuInfo = this.menuListAllShow.find(menu => menu.name === val[val.length - 1])
					// 存储当前菜单信息，用于菜单页title显示（title与菜单名保持一致）
					this.setMenuInfo(menuInfo);
				}
			},
			openedNames(val,oldVal){
                if(val.length > 0 && oldVal.length > 0 && val[0] === oldVal[0]){
					return 
				}
				this.$nextTick(() => {
			        this.$refs['sider-ul'].updateOpened();
			        this.$refs['sider-ul'].updateActiveName();
			    })
			},
			routeList(val) {
				this.setMenuLevel(val);
				this.menuListAll = this.flatDeep(val, Infinity);
				this.menuListAllHidden = this.menuListAll.filter(menu => !menu.hidden && menu.hidden != undefined); //所有隐藏的菜单，无层级
				this.menuListAllShow = this.menuListAll.filter(menu => menu.hidden); //所有未被隐藏的菜单，无层级
				this.initRoute();
			}
		},

    mounted() {
      this.url2Parent(this.routeListState||[],[])
			if(this.routeList.length > 0){
				this.setMenuLevel(this.routeList);
				this.menuListAll = this.flatDeep(this.routeList, Infinity);
				this.menuListAllHidden = this.menuListAll.filter(menu => !menu.hidden && menu.hidden != undefined); //所有隐藏的菜单，无层级
				this.menuListAllShow = this.menuListAll.filter(menu => menu.hidden); //所有未被隐藏的菜单，无层级
				this.initRoute();
				
			}
			this.$nextTick(() => {
				this.$refs['sider-ul'].updateOpened();
				this.$refs['sider-ul'].updateActiveName();
			})
		}
	}
</script>
<style scoped>
	/*菜单栏样式*/
	.sider-ul.ivu-menu-dark{
		position: relative!important;
		flex:1 1 auto;
        padding: 20px 2px 0 0;
        right: -2px;
		overflow-y: auto;
		position: static;
		overflow-x: hidden;
		scrollbar-width: none;
		background-color: transparent;
	}
	.sider-ul::-webkit-scrollbar {
		width: 0;
	}
	/deep/.sider-ul .ivu-menu-submenu,
	/deep/.sider-ul .ivu-menu-opened .ivu-menu-submenu-title{
		/* background: #1D252C!important; */
		background: var(--menu-bgcolor)!important;
	}
	.sider-ul .menu-item-wrapper{
		color:var(--menu-default-color)!important;
	}
	.ivu-menu-opened .menu-item-wrapper,
	.ivu-menu-child-item-active .menu-item-wrapper,
	.sider-ul > .active-menu > .ivu-menu-submenu-title > .menu-item-wrapper{
		/* color: #C81125; */
		overflow: hidden;
		color:var(--first-menu-active-color)!important;
	}
	.sider-ul .menu-item-wrapper,
	.sider-ul .ivu-menu-submenu-title,
	.sider-ul .ivu-menu-opened .ivu-menu-submenu-title{
		display: flex;
    	align-items: center;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-submenu-title{
		padding: 10px 24px 10px 14px;
    margin: 6px 0 6px 10px;
		color: var(--second-menu-color) !important;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-item{
		color: var(--third-menu-default-color) !important;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-submenu:not(.ivu-menu-opened,.ivu-menu-item-active,.ivu-menu-child-item-active,.activeMenu) .ivu-menu-submenu-title:hover{
		color:var(--menu-default-hover-color)!important;
		background: transparent;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-submenu:not(.ivu-menu-opened,.ivu-menu-item-active,.ivu-menu-child-item-active,.activeMenu) .ivu-menu-submenu-title:hover .menu-item-wrapper{
		color:var(--menu-default-hover-color)!important;
	}


	/* 三级选中 鼠标移动颜色 */
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-item:hover,
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-submenu .ivu-menu-item-active{
		margin:0 10px;
		border-radius: 3px;
		color: var(--third-menu-active-color)!important;
		background: var(--third-menu-active-bgcolor)!important;
	}
	/deep/ .sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-submenu .ivu-menu-item-active:hover{
		background: var(--third-menu-active-bgcolor)!important;
		border-radius: 2px 2px 2px 2px;;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .activeMenu > .ivu-menu-submenu-title,
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .activeMenu > .ivu-menu-submenu-title:hover,
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-item-active > .ivu-menu-submenu-title,
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-item-active > .ivu-menu-submenu-title:hover,
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-opened:not(.ivu-menu-submenu-has-parent-submenu) > .ivu-menu-submenu-title,
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-opened:not(.ivu-menu-submenu-has-parent-submenu) > .ivu-menu-submenu-title:hover{
		background: var(--first-menu-active-bgcolor)!important;
		/* background: #fff!important; */
        /* color:#C81125; */
				/* 箭头 */
        color:var(--first-menu-active-color)!important;
        font-weight: bold;
        border-radius: 4px 0 0 4px;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .activeMenu > .ivu-menu-submenu-title > .menu-item-wrapper {
		/* color:#C81125; */
		/* 一级菜单颜色 */
		overflow: hidden;
		color:var(--first-menu-active-color)!important;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical > .activeMenu > .ivu-menu-submenu-title:after,
    /deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical > .ivu-menu-opened > .ivu-menu-submenu-title:after{
        content:'';
        position:absolute;
        top:0;
        right: -2px;
        width: 2px;
        height:100%;
        /* background-color: #C81125; */
        background-color: var(--menu-border-color);
        border-radius: 0 4px 4px 0;
    }
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-opened .ivu-menu-submenu-title-icon{
		font-weight: bold;
	}
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu > .ivu-menu-submenu-title {
		padding-left: 45px!important;
	}
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu >.ivu-menu .ivu-menu-item {
		padding-left: 57px!important;
	}
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu > .ivu-menu-submenu-title:before {
		content: "";
		display: block;
		border: 8px solid transparent;
		/* border-left-color: #CBD7E2; */
		border-left-color: var(--second-menu-color);
		border-top-width: 5px;
		border-bottom-width: 5px;
		position: absolute;
		left: 28px;
    	top: 15px;
	}
	
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu.ivu-menu-child-item-active > .ivu-menu-submenu-title,
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu.ivu-menu-child-item-active > .ivu-menu-submenu-title:hover,
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu.ivu-menu-opened > .ivu-menu-submenu-title,
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu.ivu-menu-opened > .ivu-menu-submenu-title:hover{
		/* color:#C81125; */
		/* 二级 */
		color:var(--second-menu-active-color)!important;
		font-weight: bold;
		background: transparent;
		/* background: #0d1121; */
	}

	/* 二级鼠标移动字体颜色(箭头) */
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu.ivu-menu-opened > .ivu-menu-submenu-title:hover::before{
		/* border-left-color:var(--second-menu-active-color)!important; */
	}
	/deep/.sider-ul .ivu-menu-child-item-active > .ivu-menu-submenu-title:before{
		/* border-left-color: #c81125; */
		border-left-color: var(--second-menu-active-color);
	}
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu.ivu-menu-opened > .ivu-menu-submenu-title:before {
		/* border-left-color: #c81125; */
		border-left-color: var(--second-menu-active-color);
		transform: rotate(90deg);
		left: 24px;
    	top: 20px;
	}
	/deep/.sider-ul .ivu-menu-submenu-has-parent-submenu > .ivu-menu-submenu-title .ivu-icon { 
		display: none;
	}
	/deep/.sider-ul .ivu-menu{
		/* background: #0d1121; */
	}
  /deep/.sider-ul .ivu-menu-noChild .ivu-menu-submenu-title-icon{
    display: none;
  }
	.sider-ul .ivu-menu-item{
		/*background: #0d1121;*/
		margin:0 10px;
		padding: 10px 24px;
	}
	.menu-icon{
		height: 20px!important;
		margin-right: 10px;
	}
	.icon-def{
		line-height:21px;
		width: 22px;
		height: 20px;
		text-align: center;
		color:var(--menu-default-color);
		margin-right: 10px;
	}
	.icon-active{
		line-height:21px;
		width: 22px;
		height: 20px;
		text-align: center;
		/* color:#C81125; */
		color:var(--first-menu-active-color);
		margin-right: 10px;
	}
</style>
<style>
	.ivu-menu:empty{
		display: none!important;
	}
</style>
<style scoped src="./new-menu-icon.css">